package com.yvon.core.support;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author Yufeng
 */
public class DefaultMetaObjectHandler implements MetaObjectHandler {
    private final String createBy = "createBy";
    private final String createDate = "createDate";
    private final String updateBy = "updateBy";
    private final String updateDate = "updateDate";
    private final String version = "version";
    private final String deleteTag = "deleteTag";
    private static final Integer DEFAULT_VERSION = 0;
    private final MybatisPlusProperties mybatisProperties;

    public DefaultMetaObjectHandler(MybatisPlusProperties mybatisProperties) {
        this.mybatisProperties = mybatisProperties;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime localDateTime = LocalDateTime.now();
        String username = this.getUsername();
        this.setInsertFieldValByName("createBy", username, metaObject);
        this.setInsertFieldValByName("createDate", localDateTime, metaObject);
        this.setInsertFieldValByName("updateBy", username, metaObject);
        this.setInsertFieldValByName("updateDate", localDateTime, metaObject);
        this.setInsertFieldValByName("version", DEFAULT_VERSION, metaObject);
        this.setInsertFieldValByName("deleteTag", Integer.valueOf(this.mybatisProperties.getGlobalConfig().getDbConfig().getLogicNotDeleteValue()), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String username = this.getUsername();
        this.setUpdateFieldValByName("updateBy", username, metaObject);
        this.setUpdateFieldValByName("updateDate", LocalDateTime.now(), metaObject);
    }

    public String getUsername() {
        return "anonymousUser";
    }
}
